<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form
      :model="userForm"
      :rules="userRules"
      ref="userForm"
      label-width="100px"
    >
      <el-form-item label="登录名称">
        <el-input disabled v-model="userForm.username"></el-input>
      </el-form-item>

      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="userForm.nickname"></el-input>
      </el-form-item>

      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userForm.email"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="submitHandler" type="primary">提交修改</el-button>
        <el-button @click="resetHandler">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
// 2.直接将Vuex的数据赋值给data中的对象
// 不建议这么干:将Vuex的数据对象直接赋值给data中的数据,传递的地址值
// 将userForm进行双向绑定,会直接影响Vuex的数据
// 发现的现象:修改后不会影响Vue的数据为什么呢?
// 分析原因:Vuex中的userinfo是从localStorage中读取出来的,读取出来后又发送请求获取userInfo重新覆盖,所以我们在开始绑定userInfo是从loaclStorage中取出来的对象,而最后又被重新覆盖了一次
// 结论:不要将Vuex的数据进行双向绑定,因为Vuex中的数据只能通过mutations修改
// userForm:this.$store.state.userInfo
// 3.对象拷贝:Object.assign
// userForm:Object.assign({},this.$store.state.userinfo)
// 4.小技巧:利用展开运算符实现浅拷贝
import { mapState } from 'vuex'
export default {
  name: 'UserInfo',
  data () {
    return {
      // 1.老实人做法

      // userForm: Object.assign({}, this.$store.state.usrInfo),
      userForm: { ...this.$store.state.userInfo },
      userRules: {
        nickname: [
          { required: 'true', message: '请输入昵称', trigger: 'blur' },
          {
            pattern: /^\S{1,10}$/,
            message: '请输入1-10位的非空字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: 'true', message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    resetHandler () {
      // 重置表单数据并移除校验结果
      this.userForm = { ...this.$store.state.userInfo }
      this.$refs.userForm.clearValidate()
    },
    submitHandler () {
      this.$refs.userForm.validate(async (result) => {
        if (!result) return
        const { data: res } = await this.$axios.put('/my/userinfo', this.userForm)
        // console.log(res)
        if (res.code !== 0) return this.$message.error(res.message)
        // this.$message.success(res.message)
        // 更新数据
        this.$store.dispatch('getUserInfo', this.userForm)
      })
    }
  },
  computed: {
    ...mapState(['userInfo'])
  },
  created () {
    // this.$axios.put('/my/userinfo')
    // console.log(this.userInfo)
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
